﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using RecognitionForm.Handler;
using RecognitionForm.Core;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using Infrastructure.Lib.Core;

namespace RecognitionForm
{
    public partial class FrmAdd : Inherit_Window.BaseForm
    {
        public event Action<StaffInfo> ShowUpdate;

        private DataProvider dataProvider = new DataProvider();

        public FrmAdd()
        {
            InitializeComponent();
        }

        private void AddFrm_Load(object sender, EventArgs e)
        {
            comSex.Items.Add(new RecognitionForm.Handler.ListItem("Y", "男"));
            comSex.Items.Add(new RecognitionForm.Handler.ListItem("M", "女"));
            comSex.SelectedIndex = 0;
        }

        private async void btnAdd_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtName.Text) || string.IsNullOrEmpty(txtPath.Text))
            {
                MessageBox.Show("名字和头像不能为空！");
                return;
            }

            string photoBase64 = string.Empty;
            string f = txtPath.Text.Trim();
            byte[] bts;

            //判断文件文件大小，决定是否需要缩略图
            using (Image imgPhoto = Image.FromFile(f))
            {
                if (imgPhoto.Width > 430 || imgPhoto.Width < 230)
                {
                    using (var thumbImage = ImageHelper.GetThumbnailImageKeepRatio(imgPhoto, 430, 630))
                    {
                        bts = ImageHelper.Bitmap2Byte(thumbImage as Bitmap);
                    }
                }
                else
                {
                    bts = ImageHelper.GetPhotoBytes(f);
                }
            }

            if (bts != null)
            {
                photoBase64 = ImageHelper.GetPhotoBase64(bts);
            }

            StaffInfo model = new StaffInfo
            {
                code = Guid.NewGuid().ToString("N"),
                depart = txtDepart.Text.Trim(),
                name = txtName.Text.Trim(),
                gender = (comSex.SelectedItem as RecognitionForm.Handler.ListItem).Key,
                birthday = DateTime.Parse(dtBirthDay.Text),
                accAuth = 'Y',
                groupId = 1,
                photo = photoBase64
            };

            try
            {
                btnAdd.Enabled = false;
                await dataProvider.InsertStaffAsync(model);

                if (string.IsNullOrEmpty(photoBase64) || string.IsNullOrEmpty(model.name))
                {
                    MessageBox.Show("请填入人员Id、姓名、照片等信息", "Demo");
                }
                else
                {
                    char[] chArray = model.code.ToCharArray();
                    bool flag = false;
                    for (int i = 0; i < chArray.Length; i++)
                    {
                        if (chArray[i] > '\x007f')
                        {
                            flag = true;
                        }
                    }
                    if (flag)
                    {
                        MessageBox.Show("人员Id只能由英文字母和数字组成.", "Demo");
                    }
                    else
                    {
                        var owner = (this.Tag as FrmMain);
                        string s = PersonManager.CreatePerson(model.name, model.code, "2", photoBase64, owner.devSN, model.gender);
                        string str4 = string.Format("{0}\r\n", model.code);
                        byte[] bytes = Encoding.GetEncoding("GBK").GetBytes(s);
                        foreach (Socket socket in owner.CachedClients.Values)
                        {
                            if ((socket != null) && socket.Connected)
                            {
                                try
                                {
                                    socket.Send(BitConverter.GetBytes(bytes.Length));
                                    socket.Send(bytes);
                                    owner.m_SyncContext.Post(new SendOrPostCallback(owner.AddLogMessage), string.Format("上传人员到{0}成功.", socket.RemoteEndPoint.ToString()));
                                }
                                catch (Exception exception)
                                {
                                    MessageBox.Show(exception.Message, "Demo");
                                }
                            }
                        }
                    }
                }

                ShowUpdate(model);
                btnAdd.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnPath_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "标签|*.jpg;*.png;*.gif";
            ofd.RestoreDirectory = true;
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtPath.Text = ofd.FileName.ToString();
            };
        }

        private void txtPath_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtPath.Text))
            {
                return;
            }

            if (File.Exists(txtPath.Text.Trim()))
            {
                picStaff.Image = new Bitmap(txtPath.Text.Trim());
            }
        }

        private byte[] getPhotoBytes(string fileName)
        {
            byte[] bytes = null;
            try
            {
                FileInfo fi = new FileInfo(fileName);
                if (fi.Exists)
                {
                    using (FileStream fs = fi.OpenRead())
                    {
                        bytes = new byte[fi.Length];
                        fs.Read(bytes, 0, bytes.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return bytes;
        }

        private string getPhotoBase64(byte[] photoBytes)
        {
            return Convert.ToBase64String(photoBytes);
        }
    }
}
